package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.sy.cloud.wechat.model.WechatUser;
import com.sy.common.model.Juejinuser;
import com.sy.common.service.IBaseService;
import com.sy.common.service.IDbService;
import com.sy.common.service.ITestService;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by mac on 2017/11/28.
 */
@Controller
@Slf4j
@RequestMapping("/login")
public class LoginController {

    @Resource
    private IDbService dbService;

    @Resource
    private IBaseService baseService;

    @Resource
    private ITestService testService;

    @RequestMapping(value = "/regphone", method = RequestMethod.GET)
    public
    @ResponseBody
    @Rollback(false)
    String regphone(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception  {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh","CN"));
        JSONObject jsonObject = new JSONObject();

        String passwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");

        StringBuffer hql = new StringBuffer();
        hql.append("From Juejinuser where phone='");
        hql.append( phone );
        hql.append("'");
        List<Juejinuser> juejinuserList = baseService.listQuery(hql.toString(), Juejinuser.class);

        if( juejinuserList.size() > 0 ){
            jsonObject.put("message", "can't repeat reg");
            jsonObject.put("status", "0");

            response.getWriter().print(jsonObject.toJSONString());
            return "login";
        }

        Funutil funutil = new Funutil();
        passwd = funutil.encodeByMD5(passwd);
        Juejinuser juejinuser = new Juejinuser();
        juejinuser.setPhone(phone);
        juejinuser.setPassword(passwd);


        WechatUser wechatUser = testService.getWechatInfo( (String)request.getSession().getAttribute("openId") );
        juejinuser.setHeadimgurl( wechatUser.getHeadimgurl() );
        juejinuser.setUsername( wechatUser.getWechat_name() );



        testService.addUser( juejinuser );

        jsonObject.put("message","success");
        jsonObject.put("status","1");

        //  给用户登录
        SecurityUtils.getSubject().login(new UsernameToken(phone, passwd, (long) 0));
        response.getWriter().print(jsonObject.toJSONString());

        // 获取用户信息
        StringBuilder hql1 = new StringBuilder();
        hql1.append( "From Juejinuser where phone = " );
        hql1.append( phone  );

        List<Juejinuser> juejinuserList1 = baseService.listQuery( hql1.toString(), Juejinuser.class );
        Juejinuser juejinuser1 = juejinuserList1.get(0);

        request.setAttribute( "user", juejinuser1 );
        log.info("注册之后获得的user的内容");
        Gson gson = new Gson();
        log.info(gson.toJson( juejinuser1 ));

        return "index";
    }

    @RequestMapping(value = "/loginaction", method = RequestMethod.GET)
    public String loginaction(HttpServletRequest request, HttpServletResponse response) {
        String passwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        passwd = request.getParameter("pwd");
        phone = request.getParameter("phone");

        Funutil funutil = new Funutil();
        passwd = funutil.encodeByMD5(passwd);
        log.info("密码"+passwd);


        JSONObject jsonObject = new JSONObject();
    /*
        // 1.获取SecurityManager工厂，此处使用ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini");
        // 2.获取SecurityManager实例，并绑定到SecurityUtils
        SecurityManager sm = factory.getInstance();
        SecurityUtils.setSecurityManager(sm);

        // 3.得到Subject
        Subject subject = SecurityUtils.getSubject();
        // 4.创建用户登录凭证
        UsernamePasswordToken token = new UsernamePasswordToken(phone, passwd);
        // 5.登录，如果登录失败会抛出不同的异常，根据异常输出失败原因
        try {
            subject.login(token);
            // 6.判断是否成功登录
//            Assert.assertEquals(true, subject.isAuthenticated());
            System.out.println("登录成功！！");
            // 7.注销用户
//            subject.logout();
        } catch (IncorrectCredentialsException e) {
            log.info("登录密码错误");
        } catch (ExcessiveAttemptsException e) {
            log.info("登录失败次数过多");
        } catch (LockedAccountException e) {
            System.out.println(". The account for username"  + phone() +  "was locked.");
        } catch (DisabledAccountException e) {
            System.out.println("帐号已被禁用The account for username" + phone() +  "was disabled" );
        } catch (ExpiredCredentialsException e) {
            System.out.println( "帐号已过期. the account for username"  + phone() + "  was expired.");
        } catch (UnknownAccountException e) {
            System.out.println("帐号不存在. There is no user with username of"  + phone());
        }
        */


//        UsernameToken usernameToken = new AuthenticationToken()
        try {
            SecurityUtils.getSubject().login(new UsernameToken(phone, passwd, (long) 0));
        } catch (AuthenticationException e) {
            // 登录失败
            request.setAttribute("message", "账号密码错误");
            request.setAttribute("status", "0");
            return "login";
        }
        // 登录成功
        request.setAttribute("message", "success");
        request.setAttribute("status", "1");

        StringBuilder hql = new StringBuilder();
        hql.append( "From Juejinuser where phone = " );
        hql.append( phone  );

        List<Juejinuser> juejinuserList = baseService.listQuery( hql.toString(), Juejinuser.class );
        Juejinuser juejinuser = juejinuserList.get(0);


        // 登录成功之后更新昵称和头像
        WechatUser wechatUser = testService.getWechatInfo( (String)request.getSession().getAttribute("openId") );
        if( wechatUser != null ){
            juejinuser.setHeadimgurl( wechatUser.getHeadimgurl() );
            juejinuser.setUsername( wechatUser.getWechat_name() );
        }

        testService.addUser(juejinuser);


        request.setAttribute( "user", juejinuser );
        Gson gson = new Gson();
        log.info("登录之后获得的用户对象");
        log.info(gson.toJson( juejinuser ) );

        return "index";

    }


    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();
        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken)subject.getPrincipals().getPrimaryPrincipal();
        }else{
            // 没有登录
            response.getWriter().print("0");
            return;
        }
        StringBuilder hql = new StringBuilder();
        hql.append( "From Juejinuser where phone = " );
        hql.append( token.getPhone()  );

        List<Juejinuser> juejinuserList1 = baseService.listQuery( hql.toString(), Juejinuser.class );
        Juejinuser juejinuser1 = juejinuserList1.get(0);

        request.setAttribute( "user", juejinuser1 );
        log.info("获得的user的内容");
        Gson gson = new Gson();
        log.info(gson.toJson( juejinuser1 ));
        response.getWriter().print( gson.toJson( juejinuser1) );
    }

    @RequestMapping(value = "/getWechatInfo", method = RequestMethod.GET)
    public void getWechatInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String open_id = (String)request.getSession().getAttribute("openId");
        log.info("交易代码获取到的session"+(String)request.getSession().getAttribute("openId"));



        HttpSession session=request.getSession();//获取session
        String[]   names   =   session.getValueNames();
        for   (int   i   =   0;   i   <   names.length;   i++)   {
            log.info("交易代码获取到的session"+names[i]+"，"+ session.getValue(names[i]) );
        }



        WechatUser wechatUser = testService.getWechatInfo( open_id );

        if( wechatUser == null ){
            response.getWriter().print( "none" );
        }else{
            Gson gson = new Gson();
            response.getWriter().print( gson.toJson( wechatUser) );
        }

    }





}
